<template>
  <div>
    <el-container>
      <el-main>
        <el-container class="parent-body">
          <el-header class="content-header">
            平台信息设置
          </el-header>
          <el-main class="info-main">
            <el-row>
              <el-col style="height: 100%;" :span="10" :offset="6">
                <el-form ref="form" :rules="rules" :model="platform" label-width="150px">
                  <el-form-item label="平台名称：" prop="name">
                    <el-input class="input-width" maxLength=50 v-model="platform.name"></el-input>
                  </el-form-item>
                  <el-form-item label="平台标题：" prop="title">
                    <el-input class="input-width" maxLength=100 v-model="platform.title"></el-input>
                  </el-form-item>
                  <el-form-item label="平台描述：" prop="description">
                    <el-input class="input-width" maxLength=255 v-model="platform.description"></el-input>
                  </el-form-item>
                  <el-form-item label="关键词：" prop="keywords">
                    <el-input class="input-width" maxLength=100 v-model="platform.keywords"></el-input>
                  </el-form-item>
                  <el-form-item prop="name" label="平台LOGO：">
                    <el-upload
                            class="upload-demo"
                            ref="upload"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :http-request="modeUpload"
                            :on-success="handleAvatarSuccess"
                            :limit="1"
                            :file-list="fileList"
                            :before-upload="beforeAvatarUpload"
                            list-type="picture">
                      <el-button style="margin-left: 10px;" size="small" icon="el-icon-upload" @click="submitUpload">选择上传文件</el-button>
                      <div slot="tip" class="el-upload__tip">只能上传jpg/png格式文件，文件不能超过50kb</div>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="客服热线：" prop="hotline">
                    <el-input class="input-width" maxLength=255 v-model="platform.hotline"></el-input>
                  </el-form-item>
                  <el-form-item label="客服邮箱：" prop="email">
                    <el-input class="input-width" maxLength=255 v-model="platform.email"></el-input>
                  </el-form-item>
                  <el-form-item label="内容：" >
                    <el-input style="position:relative;"
                              type="textarea"
                              :rows="7"
                              maxLength=1000
                              placeholder="请输入内容"
                              v-model="platform.content">
                    </el-input>
                    <div style="font-size:12px;color:#999999;">该信息将在用户中心欢迎页面显示</div>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm('form')">提交</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </el-main>
    </el-container>
  </div>
</template>
<script>
    import goodImgeListApi from "@/api/goods/imagelist";
    export default {
        data() {
            // 验证邮箱
            var validateEMail = (rule, value, callback) => {
                const reg =/^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
                if(value==''||value==undefined||value==null){
                    callback();
                }else{
                    if (!reg.test(value)){
                        callback(new Error('请输入正确的邮箱地址'));
                    } else {
                        callback();
                    }
                }
            }
            /* 是否手机号码或者固话*/
            var validatePhoneTwo =(rule, value, callback) => {
                const reg = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/;
                if (value == '' || value == undefined || value == null) {
                    callback();
                } else {
                    if ((!reg.test(value)) && value != '') {
                        callback(new Error('请输入正确的电话号码'));
                    } else {
                        callback();
                    }
                }
            }
            return {
                requestUrl:goodImgeListApi.getRequestUrl().defaults.baseURL+'/api-sys/platform/',
                imgUrl:goodImgeListApi.getRequestUrl().defaults.baseURL+"/api-goods/album/",
                platform:{
                    name:'',
                    title:'',
                    description:'',
                    keywords:'',
                    hotline:'',
                    email:'',
                    content:''
                },
                imageUrl:'',
                mode:"",
                rules: {
                    name: [
                        {required: true, message: '请输入平台名称', trigger: 'blur'}
                    ],
                    title: [
                        {required: true, message: '请输入平台标题', trigger: 'blur'}
                    ],
                    description: [
                        {required: true, message: '请输入平台描述', trigger: 'blur'}
                    ],
                    keywords: [
                        {required: true, message: '请输入平台关键字', trigger: 'blur'}
                    ],
                    hotline: [
                        {required: true, message: '请输入客服热线', trigger: 'blur'},
                        {validator:validatePhoneTwo,trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入客服邮箱', trigger: 'blur'},
                        {validator:validateEMail,trigger: 'blur'}
                    ],
                },
                fileList:[],
            }
        },
        methods:{
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if(this.mode=="" && this.fileList.length==0){
                            this.$message.error('请选择平台LOGO');
                            return ;
                        }
                        let param = new FormData(); //创建form对象
                        param.append('file',this.mode);
                        param.append('name',this.platform.name);
                        param.append('title',this.platform.title);
                        param.append('description',this.platform.description);
                        param.append('keywords',this.platform.keywords);
                        param.append('hotline',this.platform.hotline);
                        param.append('email',this.platform.email);
                        param.append('content',this.platform.content);
                        let config = {
                            headers:{'Content-Type':'multipart/form-data'} //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
                        };
                        this.axios.post(this.requestUrl+"save?token=11",param,config).then((response) => {
                            if(response.data.error_no == 0){
                                this.$message({
                                    type: 'success',
                                    message: response.data.error_info
                                });
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: response.data.error_info
                                });
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            submitUpload() {
                this.$refs.upload.submit();
            },

            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            handleRemove() {
                this.fileList=[];
            },
            modeUpload: function(item){
                this.mode = item.file;
            },
            beforeAvatarUpload(file) {
                const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
                const isLt50K = file.size /1024 < 50;
                if (!isJPG) {
                    this.$message.error('广告图片只能是 JPG和PNG 格式!');
                }
                if (!isLt50K) {
                    this.$message.error('广告图片大小不能超过 50K!');
                }
                return isJPG && isLt50K;
            },
            handlePreview(file) {
                console.log(file);
            },
            initData(){
                this.axios.get(this.requestUrl+"get?token=1").then((response) => {
                    if(response.data.error_no == 0){
                        this.platform = response.data.results;
                        if(response.data.results.logo!="" && response.data.results.logo !=null) {
                            this.fileList.push({name: "", url: this.imgUrl + response.data.results.logo});
                        }
                    }
                })
            }
        },
        mounted() {
            this.initData();
        }
    }
</script>
<style scoped>
  .content-header{
    position: relative;
  }
  .return-style{
    position: absolute;
    right:10px;
  }
  .input-width{
    width:250px;
  }
</style>